<template>
  <div>
    <div class="request" v-if="!contractSealAddShow && !contractSealDtlShow">
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
          v-if="route.name === 'ContractSeal'"
          v-hasPermi="['system:contractSeal:query']"
          class="btn search"
          @click="getContractSealList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          v-if="route.name === 'SealCheck'"
          v-hasPermi="['system:sealCheck:query']"
          class="btn search"
          @click="getContractSealList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          v-if="route.name === 'ContractSeal'"
          v-hasPermi="['system:contractSeal:add']"
          class="btn search"
          @click="
            contractSealAddShow = true;
            pageType = 'add';
          "
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >新增</el-button
        >
        <el-button
          v-if="route.name === 'ContractSeal'"
          v-hasPermi="['system:contractSeal:export1']"
          class="btn save"
          @click="handleExport('1')"
          ><el-icon class="icon" color="#fff"> <Download /> </el-icon
          >导出列表</el-button
        >
        <!-- <el-button
          v-if="route.name === 'ContractSeal'"
          v-hasPermi="['system:contractSeal:export2']"
          class="btn save"
          @click="handleExport('2')"
          ><el-icon class="icon" color="#fff"> <Download /> </el-icon
          >导出明细</el-button
        > -->
        <el-button class="btn add" @click="handleRefresh"
          ><el-icon class="icon" color="#fff"> <Refresh /> </el-icon
          >重置</el-button
        >
        <el-popover :width="170" trigger="click" placement="bottom">
          <template #reference>
            <el-button class="btn search" style="width: 100px"
              ><el-icon class="icon" color="#fff"> <Setting /> </el-icon
              >显示列</el-button
            >
          </template>
          <el-checkbox-group v-model="checkList" @change="handleCheckChange">
            <div>
              <el-checkbox label="purchaseContractCode">合同编号</el-checkbox>
            </div>
            <div>
              <el-checkbox label="purchaseContractName">合同名称</el-checkbox>
            </div>
          
            <div>
              <el-checkbox label="contractTypeName">合同类型</el-checkbox>
            </div>
            <div>
              <el-checkbox label="purchaseTypeName">采购类型</el-checkbox>
            </div>
            <div>
              <el-checkbox label="applicantName">经办人</el-checkbox>
            </div>
            <div>
              <el-checkbox label="deptName">经办部门</el-checkbox>
            </div>
            <div>
              <el-checkbox label="applicantDate">申请日期</el-checkbox>
            </div>
            <div>
              <el-checkbox label="contractCheckStatusName"
                >审核状态</el-checkbox
              >
            </div>
            <div>
              <el-checkbox label="paymentAmount">合同金额(元)</el-checkbox>
            </div>
          
            <div>
              <el-checkbox label="distributorName">供应商</el-checkbox>
            </div>
            <div>
              <el-checkbox label="createUserName">创建人员</el-checkbox>
            </div>
            <div>
              <el-checkbox label="createTime">创建时间</el-checkbox>
            </div>
          </el-checkbox-group>
        </el-popover>
      </div>
      <!-- 筛选条件 -->
      <div class="search">
        <div class="search-item" style="margin-bottom: 10px">
          <el-input
            clearable
            v-model="params.purchaseContractCode"
            class="search-input"
            placeholder="请输入合同编号"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.purchaseContractName"
            class="search-input"
            placeholder="请输入合同名称"
          ></el-input>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.contractType"
            placeholder="请选择合同类型"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in contractStatusList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.applicantName"
            class="search-input"
            placeholder="请输入经办人"
          ></el-input>
        </div>
      

       

        <div class="search-item">
          <el-select
            v-model="params.contractCheckStatus"
            placeholder="请选择审核状态"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in auditStatusList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>

       

        <div class="search-item">
          <el-date-picker
            v-model="time"
            type="daterange"
            align="right"
            range-separator="至"
            start-placeholder="申请开始日期"
            end-placeholder="结束日期"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
          <!-- class="search-input" -->
        </div>
      </div>

      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="contractSealList"
        border
        height="59.2vh"
        :header-cell-style="{ 'text-align': 'center' }"
        @sort-change="sortChange"
      >
        <el-table-column label="操作" width="150px">
          <template #default="{ row }">
            <div class="table-operate">
              <el-icon
                v-if="
                  route.name === 'ContractSeal' &&
                  [0, 5, 6].includes(row.contractCheckStatus)
                "
                v-hasPermi="['system:contractSeal:edit']"
                title="编辑"
                color="#FFB700"
                class="table-icon"
                :size="20"
                @click="handleOperate('edit', row)"
              >
                <Edit />
              </el-icon>
              <el-icon
                v-if="route.name === 'ContractSeal'"
                v-hasPermi="['system:contractSeal:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>
              <el-icon
                v-if="route.name === 'SealCheck'"
                v-hasPermi="['system:sealCheck:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>
              <!-- route.name === 'SealCheck' && -->
              <el-icon
                v-if="
                  [1, 2].includes(row.contractCheckStatus) &&
                  row.contractType !== 4 &&
                  row.auditStatus == 1
                "
                v-hasPermi="['system:ContractSeal:check']"
                title="审核"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('check', row)"
              >
                <Checked />
              </el-icon>
              <!-- -->
              <el-icon
                v-if="
                  route.name === 'ContractSeal' &&
                  [0, 5].includes(row.contractCheckStatus)
                "
                v-hasPermi="['system:contractSeal:remove']"
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'SealCheck' &&
                  [0, 5].includes(row.contractCheckStatus) &&
                  false
                "
                v-hasPermi="['system:sealCheck:remove']"
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
              <el-icon
                v-hasPermi="['system:contractSeal:revoke']"
                v-if="
                  route.name === 'ContractSeal' && row.contractCheckStatus == 1
                "
                title="撤销"
                color="#BBBBBB"
                class="table-icon"
                :size="20"
                @click="handleOperate('revoke', row)"
              >
                <!-- <Refresh /> -->
                <img
                  src="@/assets/icons/images/repeal.png"
                  style="width: 18px; height: 18px"
                />
              </el-icon>
            </div> </template
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          width="70"
          align="center"
        />
        <el-table-column
          label="合同编号"
          v-if="checkList.includes('purchaseContractCode')"
          prop="purchaseContractCode"
          :show-overflow-tooltip="true"
          width="240"
          sortable="custom"
        />

        <el-table-column
          label="合同名称"
          v-if="checkList.includes('purchaseContractName')"
          prop="purchaseContractName"
          :show-overflow-tooltip="true"
          width="240"
          sortable="custom"
        />
        <el-table-column
          label="合同类型"
          v-if="checkList.includes('contractTypeName')"
          prop="contractTypeName"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />
        <el-table-column
          label="采购类型"
          v-if="checkList.includes('purchaseTypeName')"
          prop="purchaseTypeName"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />
        <el-table-column
          label="经办人"
          v-if="checkList.includes('applicantName')"
          prop="applicantName"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />
        <el-table-column
          label="经办部门"
          v-if="checkList.includes('deptName')"
          prop="deptName"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />
        <el-table-column
          label="申请日期"
          v-if="checkList.includes('applicantDate')"
          prop="applicantDate"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />

       
        <el-table-column
          label="审核状态"
          v-if="checkList.includes('contractCheckStatusName')"
          prop="contractCheckStatusName"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            <span
              v-if="
                (row.contractType == 3 || row.contractType == 4) &&
                row.contractCheckStatus !== 0 &&
                row.contractCheckStatus !== 5
              "
              >—</span
            >
            <span v-else :style="getStatusColor(row.contractCheckStatusName)">{{
              row.contractCheckStatusName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="合同金额(元)"
          v-if="checkList.includes('paymentAmount')"
          prop="paymentAmount"
          :show-overflow-tooltip="true"
          width="150"
          sortable="custom"
        >
          <template #default="{ row }">
            <span>{{ row.paymentAmount ? row.paymentAmount : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="供应商"
          v-if="checkList.includes('distributorName')"
          prop="distributorName"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />
        <el-table-column
          label="创建人员"
          prop="createUserName"  v-if="checkList.includes('createUserName')"
          :show-overflow-tooltip="true"
          width="130"
          sortable="custom"
        />
        <el-table-column
          label="创建时间"
          prop="createTime"  v-if="checkList.includes('createTime')"
          :show-overflow-tooltip="true"
          width="160"
          sortable="custom"
        />
        <!-- <el-table-column
          label="采购总金额(元)"
          v-if="checkList.includes('purchaseAmountSum')"
          prop="purchaseAmountSum"
          :show-overflow-tooltip="true"
          width="150"
          sortable="custom"
        >
          <template #default="{ row }">
            <span>{{
              row.purchaseAmountSum ? row.purchaseAmountSum : "--"
            }}</span>
          </template>
        </el-table-column> -->
        <!-- <el-table-column
          label="已付金额(元)"
          v-if="checkList.includes('paymentAmount')"
          prop="paymentAmount"
          :show-overflow-tooltip="true"
          width="150"
          sortable="custom"
        >
          <template #default="{ row }">
            <span>{{ row.paymentAmount ? row.paymentAmount : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="到票金额(元)"
          v-if="checkList.includes('totalMoney')"
          prop="totalMoney"
          :show-overflow-tooltip="true"
          width="150"
          sortable="custom"
        >
          <template #default="{ row }">
            <span>{{ row.totalMoney ? row.totalMoney : "--" }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="下步流程"
          v-if="checkList.includes('nextNodeName')"
          prop="nextNodeName"
          :show-overflow-tooltip="true"
          min-width="150"
          sortable="custom"
        /> -->
<!-- 
        <el-table-column
          label="入库状态"
          v-if="checkList.includes('storageStatus')"
          prop="storageStatus"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            <span>{{ row.storageStatus ? row.storageStatus : "--" }}</span>
          </template>
        </el-table-column> -->
      </el-table>

      <!-- 分页 -->
      <pagination
        class="pagination"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getContractSealList"
      />
    </div>

    <ContractSealAdd
      ref="contractSealAddRef"
      v-if="contractSealAddShow"
      v-model:contractSealAddShow="contractSealAddShow"
      @refreshList="getContractSealList"
      :pageType="pageType"
    />

    <ContractSealDtl
      ref="contractSealDtlRef"
      v-if="contractSealDtlShow"
      v-model:contractSealDtlShow="contractSealDtlShow"
      @refreshList="getContractSealList"
      :pageType="pageType"
    />
  </div>
</template>

<script setup>
import { provide, inject } from "vue";
const { proxy } = getCurrentInstance();
import ContractSealAdd from "./contractSealAdd.vue";
import ContractSealDtl from "./contractSealDtl.vue";
import { deleteCustomerApi } from "@/api/information/customer";
import { getDictsApi } from "@/api/dict";
import {
  getCheckSealList,
  getSealListApi,
  deleteSealId,
  cancelSealApi,
  exportSeal,
  exportSealDetail,
} from "@/api/purchase/contractSeal";
import { addTableHeaderApi, getTableHeaderApi } from "@/api/pub";
import { ElMessage, ElMessageBox } from "element-plus";
import useUserStore from "@/store/modules/user";
// 路由
const route = useRoute();
//当前用户信息
const userStore = useUserStore();
// 搜索参数
const params = reactive({
  // applicantDate: "", // 申请日期
  applicantStartDate: "", // 申请日期
  applicantEndDate: "", // 申请日期
  applicantName: "", // 采购人
  contractCheckStatus: null, // 采购合同审核状态
  contractType: null, // 	合同类型
  purchaseContractCode: "", // 	采购合同编号
  purchaseContractName: "", // 采购合同名称
  supplierName: "", // 供应商
  storageStatus: null, // 入库状态
  pageNum: 1,
  pageSize: 50,
  sortField: "",
  sortOrder: "",
});
// 表格加载效果
const loading = ref(false);
// 客户列表
const contractSealList = ref([]);
// 合同类型
const contractStatusList = ref([]);
// 审核状态
const auditStatusList = ref([]);
// 入库状态
const inStatusList = ref([]);
//筛选时间
let time = ref([]);
// 总数
const total = ref(0);
// 客户新增组件引用
const contractSealAddRef = ref(null);
// 客户新增组件显隐
const contractSealAddShow = ref(false);

// 客户新增组件引用
const contractSealDtlRef = ref(null);
// 客户新增组件显隐
const contractSealDtlShow = ref(false);
// 操作类型
const pageType = ref("");

const checkList = ref([
  "purchaseContractCode",
  "purchaseContractName",
  "contractTypeName",
  "purchaseTypeName",
  "applicantName",
  "deptName",
  "applicantDate",
  "contractCheckStatusName",
  "paymentAmount",
  "distributorName",
  "createUserName",
  "createTime",
]);

/**
 * @description: 复选框选中
 */
const handleCheckChange = async (val) => {
  var str = val.join(",");
  const result = await addTableHeaderApi({
    moduleType: 19,
    titleField: str,
  });
};

/**
 * @description: 获取表头
 */
const getTableHeader = async () => {
  const result = await getTableHeaderApi({
    moduleType: 19,
  });
  if (result.code == 200) {
    var arr = result.data.titleField.split(",");
    checkList.value = arr;
  }
};

/**
 * @description: 重置
 */
const handleRefresh = () => {
  time.value = [];
  Object.assign(params, {
    applicantDate: "", // 申请日期
    applicantName: "", // 采购人
    contractCheckStatus: null, // 采购合同审核状态
    contractType: null, // 	合同类型
    purchaseContractCode: "", // 	采购合同编号
    purchaseContractName: "", // 采购合同名称
    supplierName: "", // 供应商
    storageStatus: null, // 入库状态
    pageNum: 1,
    pageSize: 50,
    sortField: "",
    sortOrder: "",
  });
  getContractSealList();
};

/**
 * @description: 列表排序
 * @param {*} column.prop //当前排序取的字段
 * @param {*} column.order // "desc" "asc" 正序或倒序
 */
const sortChange = (column) => {
  params.sortField = column.prop;
  if (column.order === "descending") {
    params.sortOrder = "DESC"; // 排序或倒序
  } else {
    params.sortOrder = "ASC"; // 排序或倒序
  }
  getContractSealList();
};

/**
 * @description: 获取客户列表
 */
const getContractSealList = async () => {
  try {
    loading.value = true;

    let { pageNum, pageSize } = params;
    let res;
    // if (route.name === "ContractSeal") {
    //   params.auditType = 1;
    //   res = await getSealListApi({ pageNum, pageSize }, params);
    // } else {
    // }
    if (time.value != null && time.value.length > 0) {
      params.applicantStartDate = time.value[0];
      params.applicantEndDate = time.value[1];
    } else {
      params.applicantStartDate = null;
      params.applicantEndDate = null;
    }
    params.auditType = 2;
    res = await getCheckSealList({ pageNum, pageSize }, params);
    contractSealList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};

provide("getNonContractual", getContractSealList);

/**
 * @description: 处理导出
 * @param {String} flag 1.列表 2.明细列表
 */
const handleExport = async (flag) => {
  // 日期
  const currentDate = new Date();
  const year = currentDate.getFullYear();
  let month = currentDate.getMonth() + 1; // 月份是从 0 开始计数的，因此要加1
  if (month < 10) {
    month = "0" + month;
  }
  const day = currentDate.getDate();
  let date = year + "" + month + "" + day;
  // 随机数
  let randomNum = Math.floor(Math.random() * (999 - 100 + 1) + 100);
  // 用户昵称
  let userName = userStore.name;
  // 文件名
  let fileNmae = date + userName + randomNum;
  let { pageNum, pageSize } = params;
  params.fields = checkList.value
  if (flag == 1) {
    /* 导出列表 */
    proxy.download(
      `/system/purContract/export?pageNum=${pageNum}&pageSize=${pageSize}`,
      params,
      `${fileNmae}.xlsx`,
      null,
      1
    );
  } else {
    /* 导出明细 */
    proxy.download(
      `/system/purContract/exportDetail?pageNum=${pageNum}&pageSize=${pageSize}`,
      params,
      `${fileNmae}.xlsx`,
      null,
      1
    );
  }
};
/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
const handleOperate = async (type, row) => {
  switch (type) {
    case "edit":
      pageType.value = type;
      contractSealAddShow.value = true;
      nextTick(() => {
        contractSealAddRef.value &&
          contractSealAddRef.value.handleDetailInfo(row.purchaseContractId);
      });
      break;
    case "detail":
      pageType.value = type;
      contractSealDtlShow.value = true;
      nextTick(() => {
        contractSealDtlRef.value &&
          contractSealDtlRef.value.handleDetailInfo(row.purchaseContractId);
      });
      break;
    case "check":
      pageType.value = type;
      contractSealAddShow.value = true;
      nextTick(() => {
        contractSealAddRef.value &&
          contractSealAddRef.value.handleDetailInfo(row.purchaseContractId);
      });
      break;
    case "delete":
      ElMessageBox.confirm("此操作将删除该合同用印信息，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteSealId(row.purchaseContractId);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getContractSealList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;
    case "revoke":
      ElMessageBox.confirm("此操作将撤销该合同用印信息，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          let param = {
            purchaseContractId: row.purchaseContractId,
            contractCheckStatus: 5,
          };
          const res = await cancelSealApi(param);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getContractSealList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;
    default:
      break;
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  // 合同状态
  await getDictsApi("erp_ready_contract_type").then((res) => {
    if (res.code === 200) {
      if (route.name === "ContractSeal") {
        contractStatusList.value = res.data;
        contractStatusList.value.push({ label: "补充协议", value: 6 });
      } else {
        contractStatusList.value = [
          {
            label: "项目采购",
            value: 0,
          },
          {
            label: "综合采购",
            value: 1,
          },
          {
            label: "解除协议",
            value: 2,
          },
          {
            label: "框架协议",
            value: 5,
          },
          {
            label: "补充协议",
            value: 6,
          },
        ];
      }
    }
  });

  // 审核状态
  await getDictsApi("erp_contract_check_status").then((res) => {
    if (res.code === 200) {
      auditStatusList.value = res.data;
    }
  });

  // 入库状态
  await getDictsApi("erp_in_status").then((res) => {
    if (res.code === 200) {
      inStatusList.value = res.data;
    }
  });
}

/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum;
  const pageSize = params.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}

onMounted(() => {
  getTableHeader();
  // 路由携带项目id参数，直接显示详情页
  if (route.query?.purchaseContractId) {
    let purchaseContractId = route.query.purchaseContractId;
    pageType.value = "detail";
    contractSealAddShow.value = true;
    nextTick(() => {
      contractSealAddRef.value &&
        contractSealAddRef.value.handleDetailInfo(purchaseContractId);
    });
  }
  if (route.query?.businessId) {
    let applyId = route.query.businessId;
    if (
      route.query.checkStatus === "待审核" ||
      route.query.checkStatus === "审核中"
    ) {
      pageType.value = "check";
      contractSealAddShow.value = true;
      nextTick(() => {
        contractSealAddRef.value &&
          contractSealAddRef.value.handleDetailInfo(Number(applyId));
      });
    }
  }
  if (route.query?.myinfoId) {
    let applyId = route.query.myinfoId;
    pageType.value = "detail";
    contractSealAddShow.value = true;
    nextTick(() => {
      contractSealAddRef.value &&
        contractSealAddRef.value.handleDetailInfo(Number(applyId));
    });
  }
  getDicts();
  getContractSealList();
});
</script>
<style>
@import "@/assets/styles/confirmBtn.css";
</style>
<style lang="scss" scoped>
.request {
  padding: 20px;
  width: 100%;
  height: 100%;
  .pagination {
    margin-top: 20px;
  }
  .search {
    flex-wrap: wrap;
  }
  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 200px !important;
    height: 34px !important;
  }
}
</style>
